package http

import (
	"net/http"
	"net/url"
	"strings"
	"fmt"
	"crypto/tls"
	"encoding/json"
	"log"

	"github.com/open-falcon/mail-provider/config"
	"github.com/toolkits/web/param"
	"github.com/astaxie/beego/httplib"

)

type WX_Token struct {
	Access_Token string `json:"access_token"`
	}

type Send_TXTmsg struct {
	USER  string `json:"touser"`
	PARTY string `json:"toparty"`
	TAG   string `json:"totag"`
	MSGTYPE string `json:"msgtype"`
	AGENTID	string `json:"agentid"`
	TEXT  Content `json:"text"`
	SAFE  string `json:"safe"`
        }
type Content struct {
	CONTENT string `json:"content"`
	}
var get_time int64

func configProcweixinRoutes() {

	http.HandleFunc("/sender/wchat", func(w http.ResponseWriter, r *http.Request) {
	cfg := config.Config()
	tos := param.MustString(r, "tos")
	content := param.MustString(r, "content")
	content = strings.Replace(content, "==", " 等于 ",-1)
	content = strings.Replace(content, ">=", " 大于 ",-1)
	content = strings.Replace(content, ">", " 大于 ",-1)
	content = strings.Replace(content, "<=", " 小于 ",-1)
	content = strings.Replace(content, "<", " 小于 ",-1)
	content = strings.Replace(content, "[]", "",-1)
	content = strings.Replace(content, "][", "]--[",-1)
	//content = strings.Replace(content, "[", "",-1)
	//content = strings.Replace(content, "]", "",-1)
	//content = strings.Replace(content, "(", "",-1)
	//content = strings.Replace(content, ")", "",-1)
	content = strings.Replace(content, "\n", "",-1)
	tos = strings.Replace(tos, ",", "|", -1)
	req := httplib.Get(cfg.Wchat.Token_api)
	req.Param("corpid",cfg.Wchat.Corp_id)
	req.Param("corpsecret",cfg.Wchat.Secret)
	req.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	str, err := req.String()
	if err != nil {
    		// error
	}
	//fmt.Println(str)
	var weixin_token WX_Token
	//把token的json转化成struct
	if err := json.Unmarshal([]byte(str),&weixin_token);err ==nil {
	//	fmt.Println(weixin_token)
		fmt.Println(weixin_token.Access_Token)
	}
	var text_msg Send_TXTmsg //定义文本消息结构体内容
	text_msg.USER = tos //用户id
	text_msg.PARTY = cfg.Wchat.Party_id	//部门id
	text_msg.MSGTYPE = "text"//消息类型是文本
	text_msg.AGENTID = cfg.Wchat.Agent_id //微信企业号应用id
	text_msg.TEXT.CONTENT = content
	//text_msg.TEXT.CONTENT = "P2PROBLEMUSDC104.131.38.185cpu负载高于>90+allcpu.idle9798O120170411" 
	text_msg.SAFE="0"
	
	u, _ := url.Parse(cfg.Wchat.Msg_api)
	q := u.Query()
	q.Add("access_token",weixin_token.Access_Token)
	u.RawQuery = q.Encode()
	res := httplib.Post(u.String())
	res.JSONBody(&text_msg)
	res.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	result, err := res.String()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(result)		
})

}

